const os = require('os');
const fs = require('fs');
const { exec } = require('child_process');

/**
 * 构建框架
 */
async function buildFramework(){
	return new Promise((resolve)=>{
		Editor.log(Editor.T("lcc.build_begin"));
		if(os.platform() == "win32"){
			var cwd = Editor.url('packages://lcc/', 'utf8');
			var command = "gulp buildFramework";
			return exec(command, { cwd : cwd }, (error, stdout, stderr) => {
				if (error) {
					Editor.error('error : ' + error);
				}else{
					Editor.log(stdout);
					if(stderr){
						Editor.error(stderr);
					}
					Editor.log(Editor.T("lcc.build_end"));
				}
				resolve();
			});
		}
		resolve();
	});
}

/**
 * 构建指定包声明
 * @param pack 
 */
async function buildPackDeclaration(pack){
	return new Promise((resolve)=>{
		Editor.log(Editor.T("lcc.build_begin"));
		if(os.platform() == "win32"){
			var cwd = Editor.url('packages://lcc/', 'utf8');
			var command = "gulp buildPackDeclaration --pack " + pack;
			return exec(command, { cwd : cwd }, (error, stdout, stderr) => {
				if (error) {
					Editor.error('error : ' + error);
				}else{
					Editor.log(stdout);
					if(stderr){
						Editor.error(stderr);
					}
					Editor.log(Editor.T("lcc.build_end"));
				}
				resolve();
			});
		}
		resolve();
	});
}

/**
 * 构建所有包声明
 */
async function buildPackDeclarationAll() {
	let packs = [ "main" ];
	let packpath = Editor.Project.path + "/assets/packs/";
	for(let p of fs.readdirSync(packpath)){
		let fstate = fs.statSync(packpath + p);
		if(fstate.isDirectory()){
			packs.push(p);
		}
	}
	for (let i = 0; i < packs.length; i++){
		Editor.log(Editor.T("lcc.build_progress") + "(" + (i + 1) + "/" + packs.length + ") begin ...")
		await buildPackDeclaration(packs[i]); 
		Editor.log(Editor.T("lcc.build_progress") + "(" + (i + 1) + "/" + packs.length + ") end")
	}
}

/**
 * 构建开始
 * @param options 
 * @param callback 
 */
function onBuildStart(options, callback) {
	Editor.log("onBuildStart", options);
	callback();
}

module.exports = {
	load () {
		// 当 package 被正确加载的时候执行
		//Editor.Builder.on('build-start', onBuildStart);
	},

	unload () {
		// 当 package 被正确卸载的时候执行
		//Editor.Builder.removeListener('build-start', onBuildStart);
	},

	messages: {
		'buildFramework' : async () => {
			await buildFramework();
		},

		'buildPackDeclarationAll' : async () => {
			await buildPackDeclarationAll();
		}
	},
}
